<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id"  v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="filterArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubDialogVisible=true">发表文章</el-button>
      </div>
        <!-- 发表文章的 Dialog 对话框 -->
        <el-dialog title="发表文章" :visible.sync="pubDialogVisible" fullscreen :before-close="handleClose" @closed="onDialogClosed">
                <!-- 发布文章的对话框 -->
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
            <el-input v-model.trim="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <el-option :label="item.cate_name" :value="item.id+''" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
        </el-form-item>
            <el-form-item label="文章内容" prop="content">
            <!-- 使用 v-model 进行双向的数据绑定 -->
            <quill-editor v-model.trim="pubForm.content" @change="$refs.pubFormRef.clearValidate('content')"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
            <!-- 用来显示封面的图片 -->
            <img  v-if="cover_img" :src="cover_img" alt="" class="cover-img" ref="imgRef" />
            <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input v-if="pubDialogVisible" type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="onCoverChange"/>
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
            <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form-item>
        </el-form>
        </el-dialog>
        <!-- 查看文章详情对话框 -->
        <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
            <h1 class="title">{{ artDetail.title }}</h1>
            <div class="info">
                <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
                <span>发布时间：{{ artDetail.pub_date | dateFormat }}</span>
                <span>所属分类：{{ artDetail.cate_name }}</span>
                <span>状态：{{ artDetail.state }}</span>
            </div>

            <!-- 分割线 -->
            <el-divider></el-divider>

            <!-- 文章的封面 -->
            <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

            <!-- 文章的详情 -->
            <div v-html="artDetail.content" class="detail-box"></div>
        </el-dialog>
      <!-- 文章表格区域 -->
      <!-- 文章表格区域 -->
        <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDetail(row.id)">{{ row.title }}</el-link>
        </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
            <template v-slot="{row}">
                {{ row.pub_date | dateFormat}}
            </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
            <template v-slot="scope">
                <el-button size="mini" type="danger" @click="delArt(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        >
        </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ArtList',
  data () {
    return {
      // 控制文章详情对话框的显示与隐藏
      detailVisible: false,
      // 文章的详情信息对象
      artDetail: {},
      cateList: [],
      //  文章的列表数据
      artList: [],
      total: 0,
      cover_img: null,
      // 控制发表文章对话框的显示与隐藏
      pubDialogVisible: false,
      //   定义富文本编辑器
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 5,
        cate_id: '',
        state: ''
      },
      pubForm: {
        title: '',
        cate_id: '',
        // 文章的内容
        content: '',
        cover_img: null,
        // 文章的发布状态，可选值有两个：草稿、已发布
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', tigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        //   { pattern: /^\S{1,30}$/, message: '内容不能为空', tigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', tigger: 'blur' }
        ],
        content: [
          { required: true, message: '文章内容不能为空', tigger: 'change' },
          //   { pattern: /^\S{1,}$/, message: '文章不能为空', tigger: 'blur' }
          { pattern: /^(?!<p>\s{1,}<\/p>$)/, message: '说点什么吧...', tigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '请选择文章封面', tigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async handleClose (done) {
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 取消了关闭
      if (confirmResult === 'cancel') return
      // 确认关闭
      done()
      //   封面置空
      this.cover_img = null
    },
    onDialogClosed () {
      // 清空关键数据
      this.$refs.pubFormRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.cover_img = null
      this.pubForm.state = ''
      this.$cover_img = null
    },
    // 初始化文章分类的列表数据
    async initCateList () {
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code === 0) {
        this.cateList = res.data
      }
    },
    // 初始化文章的列表数据
    async initArtList () {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      if (res.code !== 0) return
      this.artList = res.data
      this.total = res.total
    },
    chooseImg () {
      this.$refs.iptFileRef.click()
    },
    onCoverChange (e) {
      this.$refs.pubFormRef.clearValidate('cover_img')
      // 获取文件数组
      const files = e.target.files
      if (files.length === 0) {
      // 用户没有选择封面
        this.pubForm.cover_img = null
        this.cover_img = null
      } else {
      // 用户选择了封面
        this.pubForm.cover_img = files[0]
        this.cover_img = URL.createObjectURL(files[0])
      }
    },
    // 发布
    pubArticle (state) {
      // 1. 设置发布状态
      this.pubForm.state = state

      // 2. 表单预校验
      this.$refs.pubFormRef.validate(async valid => {
        // 3. 判断是否提供了文章封面
        if (this.pubForm.cover_img !== null) {
          console.log(this.pubForm.cover_img)
          this.$refs.pubFormRef.clearValidate('cover_img')
        }
        if (!valid) return this.$message.error('请完善文章信息！')
        // 4. TODO：发布文章
        // 创建 FormData对象
        const fd = new FormData()
        // 向FormData中追加数据
        Object.keys(this.pubForm).forEach(key => {
          fd.append(key, this.pubForm[key])
        })
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return
        // 重置表单和封面
        this.$refs.pubFormRef.resetFields()
        this.pubForm.cover_img = null
        this.cover_img = null
        this.pubForm.content = ''
        this.pubForm.state = ''
        this.pubDialogVisible = false
        // 刷新list页面
        this.initArtList()
      })
    },
    // 筛选按钮
    filterArtList () {
      this.q.pagenum = 1
      this.initArtList()
    },
    // 监听pageSize发生变化
    handleSizeChange (newSize) {
      // 为 pagesize赋值
      this.q.pagesize = newSize
      // 默认展示第一页数据
      this.pagenum = 1
      // 重新发起请求
      this.initArtList()
    },
    // 监听handleCurrentChange函数 监听页码发生变化
    handleCurrentChange (newPage) {
      // 为页码值赋值
      this.q.pagenum = newPage
      // 重新发起请求
      this.initArtList()
    },
    // 重置按钮
    resetList () {
      // 1. 重置查询参数对象
      this.q = {
        pagenum: 1,
        pagesize: 5,
        cate_id: '',
        state: ''
      }
      // 2. 重新发起请求
      this.initArtList()
    },
    // 删除文章
    delArt (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        //   发起请求
        this.$http.delete('/my/article/info', { params: { id: row.id } }).then(res => {
          if (res.data.code !== 0) return
          //   如果当前页只有一条了 就让它跳到前一页
          if (this.artList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          //   刷新页面数据
          this.initArtList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 展示文章详情
    async showDetail (id) {
      // 请求详情数据
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error('获取文章详情失败!')
      this.artDetail = res.data
      // 展示对话框
      this.detailVisible = true
    }
  },
  created () {
    this.initCateList()
    this.initArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }

}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
  /deep/ .ql-editor {
  min-height: 300px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
